package com.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class LoginController {

    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }

    @RequestMapping("/login")
    public String login(String userCode, String password, Model model,Integer login){
        System.out.println(login);
         if(login==null){
            return "/login";
        }
        else if(login==1){
            //1.设置令牌，用户名和密码
            UsernamePasswordToken token = new UsernamePasswordToken(userCode, password);
            System.out.println(token);
            //2.获取主体对象
            Subject subject = SecurityUtils.getSubject();
            try {
                subject.login(token);
                return "redirect:/index"; //redirect:重定向，登录、增删改
            }catch (UnknownAccountException | IncorrectCredentialsException e){
                model.addAttribute("loginErr","用户名或密码错误");
                return "/login";
            }catch (Exception e){
                return "/login";
            }
        }else if(login==2){
            //1.设置令牌，用户名和密码
            UsernamePasswordToken token = new UsernamePasswordToken(userCode, password);
            //2.获取主体对象
            Subject subject = SecurityUtils.getSubject();
            try {
                subject.login(token);
                return "redirect:/ownerindex"; //redirect:重定向，登录、增删改
            }catch (UnknownAccountException | IncorrectCredentialsException e){
                model.addAttribute("loginErr","用户名或密码错误");
                return "login";
            }catch (Exception e){
                return "/login";
            }
        }
        return "/login";
    }

    @RequestMapping("/logout")
    public String logout(){
        return "/login";
    }
}
